﻿module Sustainalytics.Routing {

    import Claims = Sustainalytics.Claims;
    import Authentication = Sustainalytics.Authentication;

    export class RoutingStateServiceProvider extends RoutingServiceProviderBase implements IRoutingStateServiceProvider, ng.IServiceProvider {

        constructor(
            private $stateProvider: ng.ui.IStateProvider,
            private $urlRouterProvider: ng.ui.IUrlRouterProvider) {

            super();

            var ctx = this;

            (<any>ctx).$get = ['$rootScope', '$q', 'ClaimsAuthorizationService', '$injector', '$state', '$stateParams', function ($rootScope, $q, ClaimsAuthorizationService, $injector, $state, $stateParams) {

                // create routing engine adapter
                var routingEngineAdapter = new RoutingStateEngineAdapter($state, $stateParams);

                return new RoutingService($rootScope, $q, ClaimsAuthorizationService, $injector, ctx.routeInfoMap, routingEngineAdapter);
            }];
        }

        public $get: any;


        // what to do when path is reached
        public state(name: string, state: ng.ui.IState, security?: RouteSecurity, requires?: string[]): RoutingStateServiceProvider {
            var ctx = this;

            ctx.routeInfoMap.addRouteInfo(
                {
                    path: state.url,
                    security: security
                });

            ctx.applyRouteResolver(state, security, name, requires);

            // add route
            ctx.$stateProvider.state(name, state);

            return ctx;
        }

        // what to do if no when is met
        public otherwise(name: string, security?: RouteSecurity, requires?: string[]): RoutingStateServiceProvider {
            var ctx = this;

            ctx.$urlRouterProvider.otherwise(name);

            return ctx;
        }


        // apply security to route by injecting additional services into route.resolve property
        private applyRouteResolver(state: ng.ui.IState, security: RouteSecurity, name: string, requires: string[]): void {
            var ctx = this;

            var authViaResolve =
                {
                    refreshTokenChecker: super.createRouteResolver(security, name, requires)
                };

            // extend resolve to include route security checking
            state.resolve = $.extend(state.resolve, authViaResolve, true);
        }
    }

    angular.module(routingModuleName).provider(routingServiceName,
        ['$stateProvider', '$urlRouterProvider', RoutingStateServiceProvider]);
}